/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.wms.controller;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pigx.wms.entity.OutStorage;
import com.pig4cloud.pigx.wms.entity.SLocation;
import com.pig4cloud.pigx.wms.service.SLocationService;
import com.pig4cloud.pigx.wms.webtools.Constants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.wms.dto.CreatePackageReturnDTO;
import com.pig4cloud.pigx.wms.dto.ERPOutStorageDTO;
import com.pig4cloud.pigx.wms.dto.OutStorageForPackageDTO;
import com.pig4cloud.pigx.wms.dto.OutStoragePageDTO;
import com.pig4cloud.pigx.wms.service.OutStorageService;
import com.pig4cloud.pigx.wms.service.SysTokenService;
import com.pig4cloud.pigx.wms.webtools.GuanYiWebToolsService;
import com.pig4cloud.pigx.wms.webtools.TJWebToolsService;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;

/**
 * 入库单信息
 *
 * @author gaoxin
 * @date 2021-04-13 14:48:32
 */
@RestController
@AllArgsConstructor
@RequestMapping("/outstorage" )
@Api(value = "outstorage", tags = "出库单信息管理")
public class OutStorageController {

    private final OutStorageService outStorageService;

	private final GuanYiWebToolsService guanYiWebToolsService;

	private final TJWebToolsService tjWebToolsService;

	private final SLocationService sLocationService;

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param outStoragePageDTO 出库单信息
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/pageForVO" )
	public R getInStoragePageForVO(Page page, OutStoragePageDTO outStoragePageDTO) {
		return R.ok(outStorageService.getOutStoragePageForVO(page, outStoragePageDTO));
	}

	@ApiOperation(value = "获取管易出库单", notes = "获取管易出库单")
	@PostMapping("/getGYOuts" )
	public R getGYTJOuts(String startDateTime, String endDateTime) {

		if(startDateTime == null || endDateTime == null){

			return R.failed("非法参数...");

		}

		String resopnseJson = guanYiWebToolsService.getDeliverys(startDateTime,endDateTime);

		JSONObject jsonObject = JSONUtil.parseObj(resopnseJson);

		boolean success = jsonObject.getBool("success");

		if(success){

			int total = jsonObject.getInt("total");

			if(total > 0){

				outStorageService.handleDSOuts(jsonObject);

				return R.ok(null,"成功获取管易出库单 出库单数量:" + total);

			}else{
				return R.ok(null,"成功获取管易出库单,但出库单数量为0");
			}

		}else{

			return R.failed("获取管易出库单失败...");

		}

	}


	/**
	 * 波次下发
	 * @param outStorageForPackageList 波次信息
	 * @return R
	 */
	 @ApiOperation(value = "波次下发", notes = "波次下发")
	 @SysLog("波次下发")
	 @PostMapping("/createPackage")
	 public R createPackage(@RequestBody List<OutStorageForPackageDTO> outStorageForPackageList) {

		 //后台校验出库单状态是否合法
		 for(OutStorageForPackageDTO osfp : outStorageForPackageList){

			 OutStorage outStorage = outStorageService.getById(osfp.getOutStorageId());

			 if(!"0".equals(outStorage.getStatus())){
				 return R.failed("WMS处理失败!","出库单"+osfp.getOutStorageId()+"状态不合法无法下发波次!");
			 }

		 }

		 CreatePackageReturnDTO createPackageReturnDTO = outStorageService.createPackageOrStockUp(outStorageForPackageList,
				 Constants.BCXF,null);

	 	if(createPackageReturnDTO.isSuccess()){
			return R.ok(createPackageReturnDTO.getMessage());
		}else{
			return R.failed("WMS处理失败!",createPackageReturnDTO.getMessage());
		}

	 }

	@ApiOperation(value = "备货下发", notes = "备货下发")
	@SysLog("备货下发")
	@PostMapping("/createStockUp")
	public synchronized R createStockUp(@RequestBody List<OutStorageForPackageDTO> outStorageForPackageList) {

		//后台校验出库单状态是否合法
		for(OutStorageForPackageDTO osfp : outStorageForPackageList){

			OutStorage outStorage = outStorageService.getById(osfp.getOutStorageId());

			if(!"0".equals(outStorage.getStatus())){
				return R.failed("WMS处理失败!","出库单"+osfp.getOutStorageId()+"状态不合法无法下发备货!");
			}

		}

		String bhlx = null;

		if(outStorageForPackageList.size() == 1){
			bhlx = Constants.SBH;
		}else{
			bhlx = Constants.DBH;
		}

		CreatePackageReturnDTO createPackageReturnDTO = outStorageService.createPackageOrStockUp(outStorageForPackageList,
				Constants.BHXF,bhlx);

		if(createPackageReturnDTO.isSuccess()){
			return R.ok(createPackageReturnDTO.getMessage());
		}else{
			return R.failed("WMS处理失败!",createPackageReturnDTO.getMessage());
		}

	}

	/**
	 * 波次单查询
	 *
	 * @param packageNo 波次单号
	 *
	 * @return
	 */
	@ApiOperation(value = "波次单查询", notes = "波次单查询")
	@GetMapping("/getPackageDetail/{packageNo}")
	public R getPackageDetail(@PathVariable("packageNo") String packageNo) {

		return R.ok(outStorageService.getPackageDetail(packageNo));
	}

	@ApiOperation(value = "出库单详情查询", notes = "出库单详情查询")
	@GetMapping("/getOutDetail/{outPageNo}")
	public R getOutDetail(@PathVariable("outPageNo") String outPageNo) {

		return R.ok(outStorageService.getOutDetail(outPageNo));
	}

	@ApiOperation(value = "更新T+系统token", notes = "更新T+系统token")
	@PutMapping("/updateTJToken")
	public R updateTJToken() {

		if(tjWebToolsService.updateToken()){
			return R.ok(null,"T+系统Token更新成功");
		}else{
			return R.failed("T+系统Token更新失败,请联系管理员");
		}

	}

	@ApiOperation(value = "获取T+出库单", notes = "获取T+出库单")
	@PostMapping("/getTJOuts" )
	public R getTJOuts(String startDateTime, String endDateTime) {

		if(startDateTime == null || endDateTime == null){

			return R.failed("非法参数...");

		}
		Map<String, ERPOutStorageDTO> erpOutStorageDTOMap =  tjWebToolsService.getTJOuts(startDateTime,endDateTime);

		if(erpOutStorageDTOMap == null || erpOutStorageDTOMap.size() == 0){
			return R.ok(null,"获取T+出库单成功,但数量为0.");
		}else{

			outStorageService.handleTJOuts(erpOutStorageDTOMap);

			return R.ok(null,"获取T+出库单成功.数量是:"+erpOutStorageDTOMap.keySet().size());
		}


	}

	@ApiOperation(value = "PC获取产线出库工作区位置", notes = "PC获取产线出库工作区位置")
	@GetMapping("/listCXOutStorageWorkStationForPC")
	public R listCXOutStorageWorkStationForPC() {

		List<SLocation> sLocationList = sLocationService.list(Wrappers.<SLocation>query().lambda()
				.eq(SLocation::getAreaId,"7").eq(SLocation::getStatus,"1")
				.eq(SLocation::getIsUsed,"0")
				.eq(SLocation::getLocationStatus,"1").orderByAsc(SLocation::getSOrder));

		return R.ok(sLocationList);

	}

	@ApiOperation(value = "修改产线出库工作区位置", notes = "修改产线出库工作区位置")
	@PutMapping("/updateOutLocation/{outPageNo}/{outLocationNo}")
	public R updateOutLocation(@PathVariable("outPageNo") String outPageNo,@PathVariable("outLocationNo") String outLocationNo) {

		OutStorage outStorage = outStorageService.getById(outPageNo);

		outStorage.setLocationNo(outLocationNo);

		if(outStorageService.updateById(outStorage)){
			return R.ok(null,"修改产线出库工作区位置成功");
		}else{
			return R.failed("修改产线出库工作区位置失败,请联系管理员");
		}

	}

}
